<template>
  <ModuleWrap title="结构物总览" class="flex h-fit flex-col justify-center">
    <div v-if="active != 0" class="relative mt-4 w-[80%]" ref="selectRef">
      <Select
        :options="structureOptions"
        v-model:value="structureId"
        @change="onChange"
        class="w-full"
        size="small"
        :getPopupContainer="() => selectRef"
      >
      </Select>
    </div>
    <Structure v-else v-model:value="treeParams" />
  </ModuleWrap>
  <!-- 告警统计 -->
  <AlarmStatistics />
  <ModuleWrap
    title="告警测点排行"
    class="flex h-[29%] flex-col justify-center"
    :module-style="{ overflow: 'hidden' }"
  >
    <TableWrap :data-source="measureRankingList" :columns="columnsRanking">
    </TableWrap>
  </ModuleWrap>
</template>

<script setup lang="tsx">
import { computed, nextTick, onMounted, ref, shallowRef, watch } from 'vue';
import {
  fetchStructureTree,
  getAlarmMeasuringPoint,
  structureList,
} from '@/pages/screen/api';
import { BoTableProps } from '@boeyo/ui';
import { Select } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import { eventBus } from '@/utils/eventMitt';
import ModuleWrap from '../ModuleWrap.vue';
import Structure from '../Structure.vue';
import TableWrap from '../TableWrap.vue';
import AlarmStatistics from '../alarm-statistics/index.vue';

const selectRef = shallowRef();

//获取当前页面参数active
const route = useRoute();
const active = ref(route.query.active || 0);
watch(
  () => route.query.active,
  (val) => {
    active.value = +val || 0;
  },
);

// 二维三维页面下拉
const structureOptions = ref([]);
const structureId = ref(history.state.structureId || '');

// 首页树型下拉
const treeData = ref();
interface Tree {
  id: number;
  children: Tree[];
  [key: string]: any;
}
const formatTree = (
  tree: Tree[],
  opt: {
    label?: string;
    value?: string;
    children?: string;
  },
) => {
  const { label = 'label', value = 'value', children = 'children' } = opt;

  const result = [];
  const stack = [...tree];
  const nodeMap = new Map();

  while (stack.length > 0) {
    const node = stack.shift();
    const formattedNode = {
      title: node[label],
      key: node[value],
      ...node,
      label: node[label],
      value: node[value],
      children: [],
    };
    nodeMap.set(node, formattedNode);
    const parentNode = nodeMap.get(node.parent);
    if (formattedNode.monitoringType == '3') return result;
    if (parentNode) {
      parentNode.children.push(formattedNode);
    } else {
      result.push(formattedNode);
    }
    if (node[children]) {
      node[children].forEach((child: any) => {
        child.parent = node;
        stack.push(child);
      });
    }
  }

  return result;
};

const init = () => {
  // 告警测点排行
  const params =
    active.value != 0 ? { structureId: structureId.value } : treeParams.value;
  getAlarmMeasuringPoint(params).then(({ data }) => {
    measureRankingList.value = data || [];
  });
  fetchStructureTree().then(async (res) => {
    treeData.value = await formatTree(res.data, {
      label: 'structureName',
      value: 'id',
    });
  });
};

// 监测阵信息切换，二维数据切换
const onChange = (params?: any) => {
  init();
  const item = structureOptions.value.find(
    (item) => item.value == structureId.value,
  );
  Object.assign(history.state, item);
  params = active.value != 0 ? { structureId: structureId.value } : params;
  eventBus.emit('changeStructure', {
    structureId: structureId.value,
    params,
    ...item,
  });
};

// 告警测点排行
const measureRankingList = ref([]);
const columnsRanking = computed<BoTableProps['columns']>(() => [
  {
    title: '排名',
    dataIndex: 'index',
    width: 40,
    customRender(opt) {
      return opt.renderIndex + 1;
    },
    ellipsis: true,
    align: 'center',
  },
  {
    title: '测点名称',
    dataIndex: 'name',
    ellipsis: true,
    align: 'center',
  },
  {
    title: '测点位置',
    dataIndex: 'location',
    ellipsis: true,
    align: 'center',
  },
  {
    title: '测点类型',
    dataIndex: 'type',
    width: 70,
    ellipsis: true,
    align: 'center',
  },
]);

onMounted(async () => {
  // 结构物总览下拉框
  const res = await structureList();
  structureOptions.value = res.data.map((i) => {
    return {
      label: i.structureName,
      value: i.structureId,
      ...i,
    };
  });
  structureId.value = structureId.value || structureOptions.value.at(0).value;
  nextTick(() => {
    init();
  });
});

// 首页树型下拉
const treeParams = ref({});
watch(
  () => treeParams.value,
  () => {
    onChange(treeParams.value);
  },
  {
    deep: true,
  },
);
</script>

<style lang="scss" scoped>
.module-wrap {
  padding-bottom: 30px;
  &:last-child {
    padding-bottom: 0;
  }
}
</style>
